import { createGlobalState } from '@peng_kai/kit/libs/vueuse';
import { useWebSocket } from './useWebSocket';
import { buildWsUrl } from './helpers';
import { proto } from './proto';

export const useAppSocket = createGlobalState(() => {
  const isAuthed = useAuthed();
  const appSocket = useWebSocket(buildWsUrl(import.meta.env.VITE_WS_URL_main), proto);

  // 当授权状态变化时断开重连
  // 开发环境下有bug（断开重连后还会使用原来的初始的URL），但不影响线上环境
  watch(isAuthed, () => {
    appSocket.disconnect();
    setTimeout(appSocket.connect, 100);
  });

  return appSocket;
});
